<template>
  <div class="report-page">
    <el-card class="toolbar-card">
      <div class="toolbar">
        <div class="title">进销存统计</div>
        <div class="actions">
          <el-button type="primary" @click="loadData">刷新</el-button>
          <el-button @click="handleExport">导出CSV</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="chart-card">
      <div ref="chartRef" class="chart" />
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="#" width="60" />
        <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label" show-overflow-tooltip />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { reportApi } from '@/api/report/report'

const loading = ref(false)
const tableData = ref([])
const chartRef = ref(null)
let chart

// 列标题映射表 - 只保留需要显示的字段
const columnMapping = {
  name: '名称',
  productName: '产品名称',
  categoryName: '分类名称',
  inQuantity: '入库数量',
  outQuantity: '出库数量',
  stockQuantity: '结存数量',
  inAmount: '入库金额',
  outAmount: '出库金额',
  stockAmount: '结存金额',
  date: '日期',
  month: '月份',
  year: '年份',
  warehouseName: '仓库名称',
  unit: '单位'
}

const columns = computed(() => {
  if (!tableData.value.length) return []
  // 只显示有数据的字段，过滤掉空值字段
  const dataKeys = Object.keys(tableData.value[0]).filter(key => {
    const hasData = tableData.value.some(item => item[key] !== null && item[key] !== undefined && item[key] !== '')
    return hasData && columnMapping[key]
  })
  return dataKeys.map(key => ({
    prop: key,
    label: columnMapping[key] || key
  }))
})

const pickNameKey = (item) => Object.keys(item).find(k => typeof item[k] === 'string') || 'name'
const pickValueKeys = (item) => Object.keys(item).filter(k => typeof item[k] === 'number').slice(0, 3)

const renderChart = () => {
  if (!chart) { 
    chart = echarts.init(chartRef.value)
    window.addEventListener('resize', () => chart && chart.resize()) 
  }
  if (!tableData.value.length) { 
    chart.clear()
    return 
  }
  
  // 获取X轴数据，优先使用有意义的字段，避免显示"未知"
  const x = tableData.value.map(i => {
    // 优先使用产品名称，如果没有则使用分类名称，再没有则使用日期
    if (i.productName && i.productName.trim()) return i.productName
    if (i.categoryName && i.categoryName.trim()) return i.categoryName
    if (i.name && i.name.trim()) return i.name
    if (i.date && i.date.trim()) return i.date
    if (i.month && i.month.trim()) return i.month
    if (i.year && i.year.trim()) return i.year
    return '未命名项目'
  })
  
  // 获取Y轴数据，确保数据类型正确
  const inQty = tableData.value.map(i => {
    const val = i.inQuantity || 0
    return typeof val === 'number' ? val : parseFloat(val) || 0
  })
  const outQty = tableData.value.map(i => {
    const val = i.outQuantity || 0
    return typeof val === 'number' ? val : parseFloat(val) || 0
  })
  const stockQty = tableData.value.map(i => {
    const val = i.stockQuantity || 0
    return typeof val === 'number' ? val : parseFloat(val) || 0
  })
  

  
  chart.setOption({
    tooltip: { 
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>'
        params.forEach(param => {
          result += param.marker + param.seriesName + ': ' + param.value + '<br/>'
        })
        return result
      }
    },
    legend: { 
      data: ['入库数量', '出库数量', '结存数量'],
      top: 10
    },
    grid: {
      top: 60,
      left: 60,
      right: 60,
      bottom: 60
    },
    xAxis: { 
      type: 'category', 
      data: x, 
      axisLabel: { 
        interval: 0, 
        rotate: 30,
        fontSize: 12
      } 
    },
    yAxis: { 
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      { 
        type: 'bar', 
        name: '入库数量', 
        data: inQty,
        itemStyle: { color: '#67C23A' }
      },
      { 
        type: 'bar', 
        name: '出库数量', 
        data: outQty,
        itemStyle: { color: '#F56C6C' }
      },
      { 
        type: 'line', 
        name: '结存数量', 
        data: stockQty,
        itemStyle: { color: '#409EFF' },
        lineStyle: { width: 3 }
      }
    ]
  })
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await reportApi.getInventoryFlow()
    const list = Array.isArray(res) ? res : (res?.data || [])
    tableData.value = list
    await nextTick(); renderChart()
  } catch (e) {
    console.error('获取进销存统计失败:', e)
    ElMessage.error('获取进销存统计失败')
  } finally { loading.value = false }
}

const handleExport = () => {
  if (!tableData.value.length) return ElMessage.warning('暂无数据可导出')
  const headers = columns.value.map(col => col.label)
  const rows = tableData.value.map(r => columns.value.map(col => r[col.prop] ?? ''))
  const csv = '\uFEFF' + [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `进销存统计_${new Date().toISOString().slice(0,10)}.csv`
  a.click(); URL.revokeObjectURL(url)
}

onMounted(() => loadData())
</script>

<style scoped>
.report-page { display: grid; gap: 12px; }
.toolbar { display: flex; justify-content: space-between; align-items: center; }
.title { font-weight: 600; }
.chart { width: 100%; height: 420px; }
</style>
